package com.tony.util.utils;

import com.tony.util.properties.UploadFileProperties;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;

/**
 * @author x
 */
public class UploadUtil {
    private static final char SEPARATOR = '/';

    /**
     * 在原有路径添加年月的路径
     * @param source 路径
     * @return 添加完年月的路径字符串
     */
    public static String appendYearMonth(String source){
        StringBuilder stringBuilder = new StringBuilder(source);
        if(source.lastIndexOf(SEPARATOR) != source.length()-1){
            stringBuilder.append(SEPARATOR);
        }
        LocalDate localDate = LocalDate.now();
        int year = localDate.getYear();
        int month = localDate.getMonthValue();
        stringBuilder.append(year).append(SEPARATOR).append(month).append(SEPARATOR);
        return stringBuilder.toString();
    }

    /**
     * 创建当前路径的上级目录
     * @param path 当前路径
     * @throws IOException io异常
     */
    public static void createPath(Path path) throws IOException {
        if(!Files.exists(path.getParent())){
            Files.createDirectories(path.getParent());
        }
    }

    /**
     * 文件上传
     * @param in 上传的文件
     * @param suffix 上传的文件后缀
     * @param properties 域名路径等参数
     * @return 带域名的文件路径
     * @throws IOException 上传文件异常
     */
    public static String uploadFile(InputStream in, String suffix, UploadFileProperties properties) throws IOException {
        String fileName = DigestUtils.md5Hex(in) + suffix;
        String pathFile = appendYearMonth(properties.getLocalPath()) + fileName;
        Path filePath = Paths.get(pathFile);
        if(!Files.exists(filePath)){
            createPath(filePath);
            Files.copy(in,filePath);
        }
        return properties.getDomain() + pathFile;
    }
}
